package com.akillitavsiye;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;

public @SessionScoped @Named
class HelloWorld implements Serializable {
	
	private static final long serialVersionUID = -4609439327276811715L;

	private String name = "";
	
	public String getMessage() {
		return "Hello World";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getOutput() {
		
		String get="";
		if(this.name!=null && !"".equals(this.name)) 
			save(this.name);
		else
		{
			get=get();
			return get;
		}
		return name.equals("") ? "" : "Hello, " + this.name + "!";
	}
	
	public String getDate(){
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
		return dateFormat.format(Calendar.getInstance().getTime());
	}

	private String get() {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	    Key guestbookKey = KeyFactory.createKey("Guestbook", "default");
	    Query query = new Query("Guestbook", guestbookKey).addSort("date", Query.SortDirection.DESCENDING);
	    List<Entity> greetings = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(5));
	    String returnString="";
	    for (Entity greeting : greetings) {
			returnString+=greeting.getProperty("user")+";";
		}
		return returnString;
	}

	private void save(String name) {

        Key guestbookKey = KeyFactory.createKey("Guestbook", "default");
        Date date = new Date();
        Entity greeting = new Entity("Guestbook", guestbookKey);
        greeting.setProperty("user", name);
        greeting.setProperty("date", date);
        greeting.setProperty("content", "Hello "+name);
        DatastoreService datastore =DatastoreServiceFactory.getDatastoreService();
        datastore.put(greeting);
		
	}
}